//
//  LGBloodPressureChart.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/3/3.
//  癌症-居家监测-体温、血氧、体重

#import "LGCancerPatientChart.h"
#import "LGScrollView.h"
#define topMargin      viewPix(50)

#define leftMargin     viewPix(35)+iPadMargin(10)

#define lineHeight     viewPix(35)

#define scrollWidth    (Screen_W - viewPix(83))

#define scrollHeight   (lineHeight*6+viewPix(20))

@interface LGCancerPatientChart()<UIScrollViewDelegate>
/**   */
@property (nonatomic , strong)UILabel *titleLabel;
/**   */
@property (nonatomic , strong)UILabel *dayLabel;
/**   */
@property (nonatomic , strong)UILabel *unitLabel;
/**   */
@property (nonatomic , strong)LGScrollView *scrollView;
/**   */
@property (nonatomic , strong)CAShapeLayer *shapeLayer;
/**  正常范围 */
@property (nonatomic , strong)UILabel *rangeLabel;
@property (nonatomic , strong)UIView *rangeView;

/**  高 */
@property (nonatomic , strong)UIButton *highButton;
/**  正常 */
@property (nonatomic , strong)UIButton *normalButton;
/**  低 */
@property (nonatomic , strong)UIButton *lowButton;
/**   */
@property (nonatomic , strong)NSDictionary *iconDic;
/**   */
@property (nonatomic , strong)NSArray *titleArray;
/**   */
@property (nonatomic , assign)NSInteger totalCount;
/**   */
@property (nonatomic , assign)CGFloat itemWidth;
/**   */
@property (nonatomic , strong)NSMutableArray *itemArray;

@end

@implementation LGCancerPatientChart

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.iconDic = @{@"0":@{@"normal":@"体征监测-正常Normal",@"select":@"体征监测-正常Select"},@"1":@{@"normal":@"体征监测-低Normal",@"select":@"体征监测-低Select"},@"2":@{@"normal":@"体征监测-高Normal",@"select":@"体征监测-高Select"},@"3":@{@"normal":@"体征监测-正常Normal",@"select":@"体征监测-正常Select"}};
        self.itemWidth = scrollWidth/7.0;
        [self createSubView];
    }
    return self;
}

-(void)setType:(NSString *)type{
    _type = type;
    self.highButton.hidden = NO;
    self.normalButton.hidden = NO;
    self.lowButton.hidden = NO;
    self.baseView.frame = CGRectMake(viewPix(16), kMaxY(self.titleLabel.frame)+viewPix(12), Screen_W-viewPix(32), scrollHeight+topMargin+viewPix(35));
    if ([type isEqualToString:@"temperature"]) {
        //体温
        self.dayLabel.text = @"最近30天体温分布";
        self.unitLabel.text = @"体温(℃)";
        self.titleArray = @[@"45",@"43",@"41",@"39",@"37",@"35"];
        [self.highButton setTitle:@" 高烧" forState:UIControlStateNormal];
        [self.lowButton setTitle:@" 低烧" forState:UIControlStateNormal];
        
    }else if ([type isEqualToString:@"oxygen"]){
        //血氧
        self.dayLabel.text = @"最近30天血氧分布";
        self.unitLabel.text = @"血氧(%)";
        self.titleArray = @[@"100",@"95",@"90",@"85",@"80",@"75"];
        [self.highButton setTitle:@" 过高" forState:UIControlStateNormal];
        [self.lowButton setTitle:@" 过低" forState:UIControlStateNormal];
        self.highButton.hidden = YES;
        self.normalButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        self.normalButton.frame = CGRectMake(0, kMaxY(self.scrollView.frame), (Screen_W-viewPix(32))/2.0-viewPix(10), viewPix(20));
        self.lowButton.frame = CGRectMake(kMaxX(self.normalButton.frame)+viewPix(30), kMaxY(self.scrollView.frame), (Screen_W-viewPix(32))/2.0-viewPix(10), viewPix(20));
        
    }else{
        //体重
        self.dayLabel.text = @"最近30天体重分布";
        self.unitLabel.text = @"体重(kg)";
        self.titleArray = @[@"200",@"160",@"120",@"80",@"40",@"0"];
        self.highButton.hidden = YES;
        self.normalButton.hidden = YES;
        self.lowButton.hidden = YES;
        self.baseView.frame = CGRectMake(viewPix(16), kMaxY(self.titleLabel.frame)+viewPix(12), Screen_W-viewPix(32), scrollHeight+topMargin);
    }
}

-(void)setTitleArray:(NSArray *)titleArray{
    _titleArray = titleArray;
    for (NSInteger i=0; i<titleArray.count; i++) {
        //Y轴标题
        UILabel *label = [UILabel lableWithText:titleArray[i] colorString:@"#333333" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        label.frame = CGRectMake(0, topMargin+lineHeight*i, leftMargin, lineHeight);
        [self.baseView addSubview:label];
        //虚线
        LGDottedLineView *lineView = [[LGDottedLineView alloc]initWithFrame:CGRectMake(0, lineHeight*i, self.itemWidth*30+viewPix(50), lineHeight)];
        lineView.tag = 5000+i;
        [self.scrollView addSubview:lineView];
    }
    [self.scrollView bringSubviewToFront:self.rangeView];
}

//创建X轴坐标
-(void)setDayArray:(NSArray *)dayArray{
    _dayArray = dayArray;
    self.totalCount = dayArray.count>0?dayArray.count:1;
    NSInteger count = (self.totalCount>6)?6:self.totalCount;
    self.itemWidth = scrollWidth/count;
    CGFloat totalWidth = viewPix(20)+self.itemWidth*self.totalCount;
    self.scrollView.contentSize = CGSizeMake(totalWidth, scrollHeight);
    [self.scrollView setContentOffset:CGPointMake(totalWidth-scrollWidth-viewPix(10), 0)];
    //虚线宽度
    for (NSInteger i=0; i<self.titleArray.count; i++) {
        LGDottedLineView *lineView = [self viewWithTag:5000+i];
        lineView.frame = CGRectMake(0, lineHeight*i, totalWidth, lineHeight);
        [lineView setNeedsDisplay];
    }
    
    for (UIView *view in self.itemArray) {
        [view removeFromSuperview];
    }
    [self.itemArray removeAllObjects];
    if (_shapeLayer) {
        [self.shapeLayer removeFromSuperlayer];
    }
    for (NSInteger i=0; i<dayArray.count; i++) {
        NSString *dayStr = LGNSString(dayArray[i]);
        if ([self.type isEqualToString:@"weight"]) {
            NSArray *tempArray = [dayStr componentsSeparatedByString:@"-"];
            dayStr = [NSString stringWithFormat:@"%@/%@",tempArray[1],tempArray[2]];
        }
        UILabel *dayLabel = [UILabel lableWithText:dayStr colorString:@"#333333" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        dayLabel.frame = CGRectMake(viewPix(10)+self.itemWidth*i, lineHeight*5.6, self.itemWidth, lineHeight);
        dayLabel.tag = 1000+i;
        [self.scrollView addSubview:dayLabel];
        [self.itemArray addObject:dayLabel];
    }
}

-(void)setDataArray:(NSArray *)dataArray{
    _dataArray = dataArray;
    NSMutableArray *pointArray = [NSMutableArray array];
    CGFloat minValue = 0;
    CGFloat margin = 2.0;
    NSInteger lineCount = 6;
    
    if ([self.type isEqualToString:@"temperature"]) {
        //体温
        minValue = 35;
        
    }else if ([self.type isEqualToString:@"oxygen"]){
        //血氧
        minValue = 75;
        margin = 5.0;
    }else{
        margin = 40.0;
    }
    
    for (NSInteger i=0; i<dataArray.count; i++) {
        NSString *value = @"";
        NSString *staus = @"0";
        if ([dataArray[i] isKindOfClass:[NSDictionary class]]) {
            NSDictionary *tempDic = dataArray[i];
            value = LGNSString(tempDic[@"value"]);
            staus = LGNSString(tempDic[@"status"]);
        }else{
            value = LGNSString(dataArray[i]);
        }
        value = [value floatValue]<minValue?[NSString stringWithFormat:@"%f",minValue-margin/4.0]:value;
        NSDictionary *colorDic = self.iconDic[staus];
        CGFloat pointY = scrollHeight-(([value floatValue]-minValue)/margin*lineHeight+viewPix(20)+lineHeight*0.5);
        UIButton *button = [UIButton buttonWithImage:LGNSString(colorDic[@"normal"]) selectImage:LGNSString(colorDic[@"select"])];
        button.bounds = CGRectMake(0, 0, viewPix(20), viewPix(20));
        button.center = CGPointMake(viewPix(10)+self.itemWidth/2.0+self.itemWidth*i, pointY);
        button.tag = 2000+i;
        [button addTarget:self action:@selector(pointButtonTouch:) forControlEvents:UIControlEventTouchUpInside];
        [self.scrollView addSubview:button];
        [self.itemArray addObject:button];
        NSValue *point = [NSValue valueWithCGPoint:button.center];
        [pointArray addObject:point];
    }
    [self drawCurveLine:pointArray lineColor:@"#4C87FD"];
}

-(void)setRangeArray:(NSArray *)rangeArray{
    _rangeArray = rangeArray;
    CGFloat totalWidth = viewPix(20)+self.itemWidth*self.totalCount;
    if ([self.type isEqualToString:@"temperature"]) {
        //体温
        self.rangeView.frame = CGRectMake(0, lineHeight*4.5, totalWidth+viewPix(20), lineHeight*0.75);

    }else if ([self.type isEqualToString:@"oxygen"]){
        //血氧
        self.rangeView.frame = CGRectMake(0, lineHeight*0.5+2, totalWidth+viewPix(20), lineHeight-2);
        
    }else{
        //体重
        self.rangeView.hidden = rangeArray.count>1?NO:YES;
        if (rangeArray.count>1) {
            CGFloat weightTop = (200 - [rangeArray[1] integerValue])/40.0;
            CGFloat weightH = ([rangeArray[1] integerValue] - [rangeArray[0] integerValue])*(lineHeight/40.0);
            self.rangeView.frame = CGRectMake(0, lineHeight*weightTop+lineHeight*0.5, self.itemWidth*30+viewPix(20), weightH);
        }
    }
}

-(void)pointButtonTouch:(UIButton *)sender{
    NSInteger index = sender.tag%1000;
    for(NSInteger i=0; i<self.totalCount; i++){
        UIButton *button = [self viewWithTag:2000+i];
        button.selected = (index == i)?YES:NO;
    }
    CGPoint point = [self.scrollView convertPoint:sender.center toView:self.superview];
    NSLog(@">>>???>>>%f--%f",point.x,point.y);
    if ([self.type isEqualToString:@"weight"]) {
        if(self.delegate && [self.delegate respondsToSelector:@selector(showWeightAlertView:date:point:)]){
            [self.delegate showWeightAlertView:self.dataArray[index] date:self.dayArray[index] point:point];
        }
    }else{
        if(self.delegate && [self.delegate respondsToSelector:@selector(showAlertView:date:point:)]){
            [self.delegate showAlertView:self.dataArray[index] date:self.dayArray[index] point:point];
        }
    }
}


//画线
-(void)drawCurveLine:(NSArray *)arry lineColor:(NSString *)color{
    if(arry.count == 0) return;
    CGPoint startPoint = [[arry objectAtIndex:0] CGPointValue];
    CGPoint lastPoint;
    UIBezierPath *lineBeizer = [UIBezierPath bezierPath];
    [lineBeizer setLineWidth:2.0];
    [lineBeizer moveToPoint:startPoint];

    for (NSInteger i = 0;i < arry.count;i++ ) {
        if (i <arry.count-1 ) {
            CGPoint nowPoint = [[arry objectAtIndex:i] CGPointValue];
            CGPoint futPoint  = [[arry objectAtIndex:i+1] CGPointValue];
            [lineBeizer addCurveToPoint:futPoint controlPoint1:CGPointMake((nowPoint.x+futPoint.x)/2, nowPoint.y) controlPoint2:CGPointMake((nowPoint.x+futPoint.x)/2, futPoint.y)];
            if (i == arry.count-2) {
                [lineBeizer moveToPoint:futPoint];//添加连线
                lastPoint = futPoint;
            }
        }
    }
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = lineBeizer.CGPath;
    shapeLayer.fillColor = [UIColor clearColor].CGColor;
    shapeLayer.strokeColor = [UIColor colorWithString:color].CGColor;
    shapeLayer.lineWidth = 2.0;
    [self.scrollView.layer addSublayer:shapeLayer];
    self.shapeLayer = shapeLayer;
    for(NSInteger i=0; i<self.totalCount; i++){
        UIButton *highBtn = [self viewWithTag:2000+i];
        UIButton *lowBtn = [self viewWithTag:3000+i];
        [self.scrollView bringSubviewToFront:highBtn];
        [self.scrollView bringSubviewToFront:lowBtn];
    }
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if(self.delegate && [self.delegate respondsToSelector:@selector(chartViewTouchesBegan)]){
        [self.delegate chartViewTouchesBegan];
    }
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if(self.delegate && [self.delegate respondsToSelector:@selector(chartViewTouchesBegan)]){
        [self.delegate chartViewTouchesBegan];
    }
}

-(void)createSubView{
    self.backgroundColor = [UIColor clearColor];
    [self addSubview:self.titleLabel];
    [self addSubview:self.baseView];
    [self addSubview:self.titleBtn];
    [self.baseView addSubview:self.dayLabel];
    [self.baseView addSubview:self.scrollView];
    [self.baseView addSubview:self.unitLabel];
    [self.baseView addSubview:self.highButton];
    [self.baseView addSubview:self.normalButton];
    [self.baseView addSubview:self.lowButton];
    [self.scrollView addSubview:self.rangeView];
    [self.titleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.baseView.mas_top).offset(12);
        make.left.right.equalTo(self.baseView);
        make.height.equalTo(@(viewPix(40)));
    }];
}

-(UILabel *)titleLabel{
    if(!_titleLabel){
        _titleLabel = [UILabel lableWithText:@"变化趋势" colorString:@"#333333" textFont:LGFontWeight(16, UIFontWeightMedium) textAlignment:NSTextAlignmentLeft lines:1];
        _titleLabel.frame = CGRectMake(viewPix(20), viewPix(7), viewPix(100), viewPix(23));
    }
    return _titleLabel;
}

-(UIView *)baseView{
    if(!_baseView){
        _baseView = [[UIView alloc] initWithFrame:CGRectMake(viewPix(16), kMaxY(self.titleLabel.frame)+viewPix(12), Screen_W-viewPix(32), scrollHeight+topMargin+viewPix(35))];
        _baseView.backgroundColor = [UIColor whiteColor];
        _baseView.cornerRidus = 10;
    }
    return _baseView;
}

-(UIButton *)titleBtn{
    if(!_titleBtn){
        _titleBtn = [UIButton buttonWithTitle:@"血压" titleFont:LGFontWeight(16, UIFontWeightMedium) textColor:@"#282828" frame:CGRectMake(0, kMinY(self.baseView.frame), Screen_W-viewPix(32), viewPix(40))];
        _titleBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        _titleBtn.titleEdgeInsets = UIEdgeInsetsMake(0, viewPix(12), 0, 0);
        _titleBtn.backgroundColor = [UIColor whiteColor];
        _titleBtn.cornerRidus = 10;
        _titleBtn.hidden = YES;
        UIImageView *tipView = [[UIImageView alloc]initWithFrame:CGRectMake(Screen_W-viewPix(32)-viewPix(28), viewPix(12), viewPix(16), viewPix(16))];
        tipView.image = [UIImage imageNamed:@"grayTip16"];
        [_titleBtn addSubview:tipView];
    }
    return _titleBtn;
}


-(UILabel *)dayLabel{
    if(!_dayLabel){
        _dayLabel = [UILabel lableWithText:@"最近30天血压分布" colorString:@"#333333" textFont:LGFont(16) textAlignment:NSTextAlignmentLeft lines:1];
        _dayLabel.frame = CGRectMake(viewPix(12), viewPix(14), viewPix(200), viewPix(23));
    }
    return _dayLabel;
}

-(LGScrollView *)scrollView{
    if(!_scrollView){
        _scrollView = [[LGScrollView alloc] initWithFrame:CGRectMake(leftMargin, topMargin, scrollWidth, scrollHeight)];
        _scrollView.contentSize = CGSizeMake(self.itemWidth*30+viewPix(20), scrollHeight);
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.delegate = self;
    }
    return _scrollView;
}

-(UILabel *)unitLabel{
    if(!_unitLabel){
        _unitLabel = [UILabel lableWithText:@"mmHg" colorString:@"#666666" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        _unitLabel.frame = CGRectMake(3, topMargin-6, 50, viewPix(17));
    }
    return _unitLabel;
}

-(UIView *)rangeView{
    if(!_rangeView){
        _rangeView = [[UIView alloc] initWithFrame:CGRectMake(0, lineHeight*3, self.itemWidth*30+viewPix(50), lineHeight*1.25)];
        _rangeView.backgroundColor = [UIColor colorWithString:@"#E5F1FF" alpha:0.7];
    }
    return _rangeView;
}

-(UIButton *)highButton{
    if(!_highButton){
        _highButton = [UIButton buttonWithTitle:@" 高" titleFont:LGFont(15) textColor:@"#333333" imageName:@"体征监测-高"];
        _highButton.frame = CGRectMake(0, kMaxY(self.scrollView.frame), (Screen_W-viewPix(32))/3.0-viewPix(10), viewPix(20));
        _highButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    }
    return _highButton;
}

-(UIButton *)normalButton{
    if(!_normalButton){
        _normalButton = [UIButton buttonWithTitle:@" 正常" titleFont:LGFont(15) textColor:@"#333333" imageName:@"体征监测-正常"];
        _normalButton.frame = CGRectMake(kMaxX(self.highButton.frame)+viewPix(10), kMaxY(self.scrollView.frame), (Screen_W-viewPix(32))/3.0-viewPix(10), viewPix(20));
        _normalButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    }
    return _normalButton;
}

-(UIButton *)lowButton{
    if(!_lowButton){
        _lowButton = [UIButton buttonWithTitle:@" 压" titleFont:LGFont(15) textColor:@"#333333" imageName:@"体征监测-低"];
        _lowButton.frame = CGRectMake(kMaxX(self.normalButton.frame)+viewPix(10), kMinY(self.highButton.frame), (Screen_W-viewPix(32))/3.0-viewPix(10), viewPix(20));
        _lowButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    }
    return _lowButton;
}

-(NSMutableArray *)itemArray{
    if(!_itemArray){
        _itemArray = [NSMutableArray array];
    }
    return _itemArray;
}

@end
